{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0768b382",
   "metadata": {},
   "source": [
    "## 1.优化百度语音识别代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ed714ec2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 百度密钥\n",
    "API_KEY = '2iHhpUZG34qQCuGBsk4QA6vB'\n",
    "SECRET_KEY = 'uEtWumr4cKdH6mi893Lcgv7Tfeq5hPHb'\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c776fd51",
   "metadata": {},
   "outputs": [],
   "source": [
    "from bdasr import fetch_token,asr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "87150356",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SUCCESS WITH TOKEN: 24.24992a490155b4d6c131c289e70d9938.2592000.1656515703.282335-25345319 ; EXPIRES IN SECONDS: 2592000\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'24.24992a490155b4d6c131c289e70d9938.2592000.1656515703.282335-25345319'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "shen_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "shen_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c3f1a2cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "c3ad889f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 0.227230\n",
      "{\"corpus_no\":\"7103548997395571377\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"你好。\"],\"sn\":\"985852558761653923885\"}\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'{\"corpus_no\":\"7103548997395571377\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"你好。\"],\"sn\":\"985852558761653923885\"}\\n'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "asr(shen_token,\"1.wav\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e342052",
   "metadata": {},
   "source": [
    "## 2.连接图灵机器人"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ac0b1f9b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4d7a7fb6",
   "metadata": {},
   "outputs": [],
   "source": [
    "TL_KEY = \"f5863b649f624fdea1fa20f56a47d066\"\n",
    "def TL_API(key,text):\n",
    "    TL_URL = \"http://openapi.turingapi.com/openapi/api/v2\"\n",
    "\n",
    "    payload={\n",
    "        \"reqType\":0,\n",
    "        \"perception\": {\n",
    "            \"inputText\": {\n",
    "                \"text\": text\n",
    "            },\n",
    "        },\n",
    "        \"userInfo\": {\n",
    "            \"apiKey\": TL_KEY,\n",
    "            \"userId\": \"000001\"\n",
    "        }\n",
    "    }\n",
    "    res = requests.post(TL_URL,data = json.dumps(payload))\n",
    "    return res.json()['results'][0]['values']['text']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "fcfa8d90",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'TL_URL' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_9584/4002764474.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mres\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mrequests\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpost\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mTL_URL\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mdata\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mjson\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mdumps\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mpayload\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m: name 'TL_URL' is not defined"
     ]
    }
   ],
   "source": [
    "res = requests.post(TL_URL,data = json.dumps(payload))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "cf75ff67",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Response [200]>"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "3e174f85",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'intent': {'code': 4007},\n",
       " 'results': [{'groupType': 0,\n",
       "   'resultType': 'text',\n",
       "   'values': {'text': 'apiKey格式不合法!'}}]}"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5095b30",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "c80b2a1c",
   "metadata": {},
   "source": [
    "## 3.接入对话机器人的流程\n",
    "> 录制音频\n",
    "\n",
    "> 语音识别--(百度ASR接口)---音频转文本信息\n",
    "\n",
    "> 图灵API--(进行文字输入和文字回复)\n",
    "\n",
    "> (待做) 语音合成（文字信息输出音频）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ffb1ee43",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. 录制音频\n",
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "    \n",
    "# 2. 语音识别\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_output = eval(asr(xu_token,'1.wav'))['result'][0]\n",
    "\n",
    "# 3. 图灵API\n",
    "TL_API(TL_KEY,asr_output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5448d82f",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "36b3a190",
   "metadata": {},
   "source": [
    "### 语音合成测试"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af1e8600",
   "metadata": {},
   "outputs": [],
   "source": [
    "tts(xu_token,TEXT)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6200d2f5",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "cd3c0ff0",
   "metadata": {},
   "source": [
    "### 在jupyter中播放音频"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8de25aaa",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pydub import AudioSegment\n",
    "from pydub.playback import play\n",
    "song = AudioSegment.from_wav('result.wav')\n",
    "play(song)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6334eca",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "2d9cd024",
   "metadata": {},
   "source": [
    "### 智能对话机器人最终版"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1daaeb84",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition # 语音音频录制模块\n",
    "from pydub import AudioSegment # 播放音频模块\n",
    "from pydub.playback import play # 播放音频模块\n",
    "from bdasr import fetch_token,asr # token 和语音识别模块\n",
    "from bdtts import tts # 语音合成模块\n",
    "\n",
    "# 1. 录制音频\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到 wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "    \n",
    "# 2. 语音识别\n",
    "xu_token = fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_output = eval(asr(xu_token,'1.wav'))['result'][0]\n",
    "\n",
    "# 3. 图灵API\n",
    "TL_result = TL_API(TL_KEY,asr_output)\n",
    "\n",
    "# 4. 语音合成 TTS -->产生result.wav\n",
    "tts(xu_token,TL_result)\n",
    "\n",
    "# 5. 在jupyter中进行音频播放\n",
    "song = AudioSegment.from_wav('result.wav')\n",
    "play(song)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
